package com.xiguanlezz.cn.consumer;

import com.xiguanlezz.cn.consumer.proxy.JdkProxyFactory;
import com.xiguanlezz.cn.consumer.proxy.ProxyFactory;
import com.xiguanlezz.cn.consumer.proxy.config.ProxyConfig;

import java.util.Objects;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/11/12 12:37
 * @Description：服务消费者客户端实现类
 */
public class RpcClient {
    private final String serviceVersion;

    private final String serviceGroup;

    private final String serializerType;

    private long invokeTimeout;

    private final String invokeMethodType;

    public RpcClient(String serviceVersion, String serviceGroup, String serializerType, long invokeTimeout, String invokeMethodType) {
        this.serviceVersion = serviceVersion;
        this.serviceGroup = serviceGroup;
        this.serializerType = serializerType;
        this.invokeTimeout = invokeTimeout;
        this.invokeMethodType = invokeMethodType;
    }

    public RpcClient(String serviceVersion, String serviceGroup, String serializerType, String invokeMethodType) {
        this.serviceVersion = serviceVersion;
        this.serviceGroup = serviceGroup;
        this.serializerType = serializerType;
        this.invokeMethodType = invokeMethodType;
    }

    public <T> T create(Class<T> clazz) {
        ProxyFactory proxyFactory = new JdkProxyFactory<T>();
        proxyFactory.init(new ProxyConfig<>(
                clazz, serviceVersion, serviceGroup,
                serializerType, invokeTimeout, invokeMethodType,
                RpcConsumer.getInstance()
        ));
        return proxyFactory.getProxy(clazz);
    }

    public void shutdown() {
        RpcConsumer consumer = RpcConsumer.getInstance();
        if (Objects.nonNull(consumer)) {
            consumer.close();
        }
    }

}
